package com.example.controller;

import com.example.entity.Cart;
import com.example.entity.Product;
import com.example.entity.User;
import com.example.service.CartService;
import com.example.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private CartService cartService;
    
    @Autowired
    private ProductService productService;

    // 添加到购物车
    @PostMapping("/add")
    @ResponseBody
    public String addToCart(@RequestParam Long productId,
                           @RequestParam BigDecimal price,
                           HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "请先登录";
        }
        
        // 验证商品是否存在
        Product product = productService.getProductById(productId);
        if (product == null) {
            return "商品不存在";
        }
        
        try {
            cartService.addToCart(user.getId(), productId, price);
            return "success";
        } catch (Exception e) {
            return "添加失败，请重试";
        }
    }

    // 购物车页面
    @GetMapping("/list")
    public String cartList(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        
        List<Cart> cartItems = cartService.getUserCart(user.getId());
        // 获取所有商品信息
        List<Long> productIds = cartItems.stream()
                .map(Cart::getProductId)
                .collect(Collectors.toList());
        List<Product> products = productService.getProductsByIds(productIds);
        Map<Long, Product> productMap = products.stream()
                .collect(Collectors.toMap(Product::getId, p -> p));
        
        BigDecimal total = cartService.calculateTotal(user.getId());
        
        model.addAttribute("cartItems", cartItems);
        model.addAttribute("productMap", productMap);
        model.addAttribute("total", total);
        return "cart/list";
    }

    // 更新购物车商品数量
    @PostMapping("/update/{id}")
    @ResponseBody
    public String updateQuantity(@PathVariable Long id, 
                               @RequestParam Integer quantity,
                               HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "请先登录";
        }
        if (quantity < 1) {
            return "数量不能小于1";
        }
        cartService.updateQuantity(id, quantity);
        return "success";
    }

    // 删除购物车商品
    @DeleteMapping("/{id}")
    @ResponseBody
    public String deleteItem(@PathVariable Long id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "请先登录";
        }
        cartService.deleteCartItem(id);
        return "success";
    }
} 